﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArtClub.DBAL;
using ArtClub.Controller;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;

namespace ArtClub
{
    public partial class AddPieces : System.Web.UI.Page
    {
        private DataDiagramDataContext dataContext = new DataDiagramDataContext();
        private string[] type = { "Painting", "Sculpture", "Other" };
        protected void Page_Load(object sender, EventArgs e)
        {
            ddlType.DataSource = type;
            ddlType.DataBind();

            //time.InnerHtml = "300";

            //DataDiagramDataContext dataContext = new DataDiagramDataContext();
            //dataContext.CreateDatabase();


            //if (IsPostBack)
            //{
            //    if (!AsyncFileUpload1.IsUploading)
            //    {
            //        try
            //        {
            //            PieceCtr pCtr = new PieceCtr();
            //            pCtr.addPiece(txtName.Text, txtArtist.Text, txtDescription.Text, txtType.Text, Convert.ToDouble(txtPrice.Text), imagePath.Value, "na", DateTime.Now);
            //            cleanTextField();
            //            Response.Write("Piece added successfully");
            //        }
            //        catch (Exception exeption)
            //        {
            //            Response.Write("Error: " + exeption.Message);
            //        }
            //        finally
            //        {
            //            Response.End();
            //        }
            //    }
            //}
        }

        private void cleanTextField()
        {
            txtName.Text = txtArtist.Text = txtDescription.Text = txtPrice.Text = string.Empty;
            ddlType.SelectedIndex = 0;
        }

        protected void btnUploadClick(object sender, EventArgs e)
        {
            try
            {
                HttpPostedFile file = Request.Files["myFile"];
                string fil = Request.Form.Get("myFile1");

                string fname = "";
                string path = "";
                string extension = "";
                //check file was submitted
                if (file != null && file.ContentLength > 0)
                {
                    fname = Path.GetFileName(file.FileName);
                    extension = fname.Split('.').Last();
                    string[] whiteList = new string[] { "png", "gif", "jpg", "bmp" };
                    if (fname == string.Empty || extension == string.Empty || !whiteList.Contains(extension.ToLower()))
	                {
		                 throw new Exception("Invalid file type, should be an image.");
	                }
                    fname = CalculateMD5Hash(fname) + "." + extension;
                    path = Path.Combine("~/Uploads/", fname);
                    file.SaveAs(Server.MapPath(path));
                }
                PieceCtr pCtr = new PieceCtr();
                pCtr.addPiece(txtName.Text, txtArtist.Text, txtDescription.Text, ddlType.SelectedValue, Convert.ToDouble(txtPrice.Text), path, "na", DateTime.Now);
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "asdf", "bootbox.alert('Art piece added successfully.')", true);
                cleanTextField();
            }
            catch (Exception exep)
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "asdf", "bootbox.alert('Add piece failed: " + exep.Message + "')", true);
                cleanTextField();
            }
            

        }

        //protected void FileUploadComplete(object sender, EventArgs e)
        //{
        //    string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
        //    string filepath = Server.MapPath("~/Uploads/") + filename;
        //    AsyncFileUpload1.SaveAs(filepath);
        //    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "filePath", "top.$get(\"" + imagePath.ClientID + "\").value = '" + @filepath + "';", true);
        //}

        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input

            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString().Substring(0, 32);
        }

    }
}